//
//  LGDownloadBuffer.m
//  LGNetworkDemo
//
//  Created by dangwc on 2019/5/15.
//  Copyright © 2019 dangwc. All rights reserved.
//

#import "LGDownloadBuffer.h"

//缓存路径[可自定义]
static NSString * const cachesPath = @"LGCaches";

@implementation LGDownloadBuffer


+(NSString *)cachesPathWithTableName:(NSString *)dbName{
    
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath1 = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",cachesPath]];
    NSString *filePath2 = [filePath1 stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",dbName]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if(![fileManager fileExistsAtPath:filePath2]){
        [fileManager createDirectoryAtPath:filePath1 withIntermediateDirectories:YES attributes:nil error:nil];//
        [fileManager createFileAtPath:filePath2 contents:nil attributes:nil];
    }
    return filePath2;
}


+(void)removeCachesDataForTableName:(NSString *)dbName{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:[self cachesPathWithTableName:dbName] error:nil];
}

+(void)saveCachesWithTableName:(NSString *)dbName cachesDataDictionary:(NSDictionary *)dataDictionary{
    
    [self removeCachesDataForTableName:dbName];
    
    if ([dataDictionary writeToFile:[self cachesPathWithTableName:dbName] atomically:YES]) {
        NSLog(@"%@",[NSString stringWithFormat:@"%@数据缓存成功",dbName]);
    }else{
        NSLog(@"%@", [NSString stringWithFormat:@"%@数据缓存失败",dbName]);
    }
}

+(id)getCachesValueForTableName:(NSString *)dbName forKey:(NSString *)key{
    NSDictionary *data = [[NSDictionary alloc] initWithContentsOfFile:[self cachesPathWithTableName:dbName]];
    return [data valueForKey:key];
}

+(NSDictionary *)getCachesDictionaryDataForTableName:(NSString *)dbName{
    NSDictionary *data = [[NSDictionary alloc] initWithContentsOfFile:[self cachesPathWithTableName:dbName]];
    return data;
}



@end
